package com.itheima.Listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.pojo.SubjectData;
import com.itheima.pojo.TbClue;
import com.itheima.service.TbClueService;
import org.springframework.beans.factory.annotation.Autowired;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    //因为SubjectExcelListener不交给spring进行管理，需要自己new，不能注入其他对象
    //不能实现数据库操作
    public TbClueService tbClueService;
    public SubjectExcelListener() {}
    public SubjectExcelListener(TbClueService tbClueService) {
        this.tbClueService = tbClueService;
    }

    //读取excel内容，一行一行进行读取
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if(subjectData == null) {
            throw new RuntimeException("文件空!");
        }

        //一行一行读取，每次读取有两个值，第一个值一级分类，第二个值二级分类
        //判断一级分类是否重复
        TbClue existOneSubject = this.existOneSubject(tbClueService, subjectData.getOneSubjectName());
        if(existOneSubject == null) { //没有相同一级分类，进行添加
            existOneSubject = new TbClue();
            existOneSubject.setId(0L);
            existOneSubject.setName(subjectData.getOneSubjectName());//一级分类名称
            tbClueService.save(existOneSubject);
        }

        //获取一级分类id值
        Long pid = existOneSubject.getId();

        //添加二级分类
        //判断二级分类是否重复
        TbClue existTwoSubject = this.existTwoSubject(tbClueService, subjectData.getTwoSubjectName(), String.valueOf(pid));
        if(existTwoSubject == null) {
            existTwoSubject = new TbClue();
            existTwoSubject.setId(pid);
            existTwoSubject.setName(subjectData.getTwoSubjectName());//二级分类名称
            tbClueService.save(existTwoSubject);
        }
    }

    //判断一级分类不能重复添加
    private TbClue existOneSubject(TbClueService tbClueService, String name) {
        QueryWrapper<TbClue> wrapper = new QueryWrapper<>();
        wrapper.eq("name",name);
        wrapper.eq("id","0");
        TbClue oneSubject = tbClueService.getOne(wrapper);
        return oneSubject;
    }

    //判断二级分类不能重复添加
    private TbClue existTwoSubject(TbClueService tbClueService,String name,String pid) {
        QueryWrapper<TbClue> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        TbClue twoSubject = tbClueService.getOne(wrapper);
        return twoSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}